<?php

namespace addons\Patrol\common\models;

use Yii;

/**
 * This is the model class for table "{{%addon_oa_record}}".
 *
 * @property int $id ID
 * @property int $member_id 用户
 * @property int $place_id 地点
 * @property string $mark 备注
 * @property string $covers 图片
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 修改时间
 */
class PatrolRecord extends \common\models\base\BaseModel
{
    public $label;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%addon_patrol_record}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['classes_id','state','covers'], 'required'],
            [['merchant_id', 'member_id',  'state', 'status', 'created_at', 'updated_at'], 'integer'],
            [['place_id','classes_id'], 'safe'],
            [['mark','label','begin_time','end_time'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'member_id' => '用户',
            'place_id' => '巡更地点',
            'classes_id' => '班次',
            'mark' => '说明',
            'picture' => '主图',
            'covers' => '图片',
            'state' => '状态',
            'begin_time' => '开始时间',
            'end_time' => '结束时间',
            'status' => '状态',
            'created_at' => '巡逻时间',
            'updated_at' => '修改时间',
        ];
    }

    /**
     * 关联用户
     *
     * @return \yii\db\ActiveQuery
     */
    public function getMember()
    {
        return $this->hasOne(\common\models\merchant\Member::class, ['id' => 'member_id']);
    }

    /**
     * 关联巡更点
     *
     * @return \yii\db\ActiveQuery
     */
    public function getPlace()
    {
        return $this->hasOne(PatrolPlace::class, ['id' => 'place_id']);
    }

    public function getPatrolClasses()
    {
        return $this->hasOne(PatrolClasses::class, ['id' => 'classes_id']);
    }

    public function beforeSave($insert)
    {
        if (Yii::$app->id == 'backend'||Yii::$app->id == 'merchant')
            $member_id = Yii::$app->user->id;
        else
            $member_id = Yii::$app->user->identity->member_id;
        $this->member_id = $member_id;
        $this->merchant_id = Yii::$app->user->identity->merchant_id;

//        if (Yii::$app->id != 'backend'||Yii::$app->id == 'merchant')
//            $this->place_id = PatrolPlace::find()->andWhere(['label'=>$this->label])->scalar();
        // 更新系统主图
        $covers = \yii\helpers\Json::decode($this->covers);
        $this->picture = $covers[0] ?? '';
        return parent::beforeSave($insert);
    }
}